package com.yuqih.common.service.impl;

import java.util.Set;

import com.yuqih.common.config.IFrameworkConfig;
import com.yuqih.common.dto.IFieldSpecified;
import com.yuqih.common.dto.TypeDescriptor;
import com.yuqih.common.service.IConvertBuilder;

public abstract class AbstractConvertBuilder<S, T> implements IConvertBuilder<S, T> {
	
	protected TypeDescriptor sourceDescriptor;
	protected TypeDescriptor targetDescriptor;
	
	/**
	 * @param modelType
	 * @param entityType
	 * @param frameworkConfig
	 */
	AbstractConvertBuilder(Class<?> sourceType, Class<?> targetType, IFrameworkConfig frameworkConfig) {
		super();
		this.sourceDescriptor = frameworkConfig.getTypeDescriptor(sourceType);
		this.targetDescriptor = frameworkConfig.getTypeDescriptor(targetType);
	}

	@Override
	public void build(S source, T target) {
		
		Set<String> fields;
		if (source instanceof IFieldSpecified) {
			IFieldSpecified fieldSpecified = (IFieldSpecified)source;
			fields = fieldSpecified.getSettedFieldNames();
		} else {
			fields = sourceDescriptor.getFieldNames();
		}
		
		build(source, target, fields);
		
	}
	
	@Override
	public void build(S source, T target, Set<String> fields) {
		if (fields == null) {
			return;
		}
				
		for (String field : fields) {
			build(source, target, field);
		}
	}
	
	protected abstract void build(S source, T target, String field);

}
